package br.com.doclayer.cmis;

import java.util.Iterator;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;

import br.com.doclayer.ItemIterable;
import br.com.doclayer.ObjectMetadata;

public class ItemIterableImpl<T> implements ItemIterable<T> {

  @SuppressWarnings("rawtypes")
  private org.apache.chemistry.opencmis.client.api.ItemIterable cmisItemIterable;

  /**
   * @param cmisItemIterable
   */
  @SuppressWarnings("rawtypes")
  public ItemIterableImpl(
      org.apache.chemistry.opencmis.client.api.ItemIterable cmisItemIterable) {
    super();
    this.cmisItemIterable = cmisItemIterable;
  }

  @Override
  public ItemIterable<T> skipTo(long position) {
    return new ItemIterableImpl<T>(this.cmisItemIterable.skipTo(position));
  }

  @Override
  public ItemIterable<T> getPage() {
    return new ItemIterableImpl<T>(this.cmisItemIterable.getPage());
  }

  @Override
  public ItemIterable<T> getPage(int maxNumItems) {
    return new ItemIterableImpl<T>(this.cmisItemIterable.getPage(maxNumItems));
  }

  @Override
  public Iterator<T> iterator() {
    Iterator<T> result = new Iterator<T>() {
      @Override
      public boolean hasNext() {
        return ItemIterableImpl.this.cmisItemIterable.iterator().hasNext();
      }

      @SuppressWarnings("unchecked")
      @Override
      public T next() {
        ObjectMetadata result;
        CmisObject object = (CmisObject) ItemIterableImpl.this.cmisItemIterable
            .iterator().next();

        if (object instanceof Folder) {
          result = new FolderCMISImpl((Folder) object);
        } else if (object instanceof Document) {
          result = new ContentCMISImpl((Document) object);
        } else {
          result = new ObjectCMISImpl(object);
        }

        return (T) result;
      }

      @Override
      public void remove() {
        ItemIterableImpl.this.cmisItemIterable.iterator().remove();
      }
    };

    return result;
  }

  @Override
  public long getPageNumItems() {
    return this.cmisItemIterable.getPageNumItems();
  }

  @Override
  public boolean getHasMoreItems() {
    return this.cmisItemIterable.getHasMoreItems();
  }

  @Override
  public long getTotalNumItems() {
    return this.cmisItemIterable.getTotalNumItems();
  }

}
